import { ref, computed } from 'vue';
import { getMessages, languageMap } from '@/locales';

// 全局语言状态，支持本地存储
const currentLanguage = ref(localStorage.getItem('app-language') || "English");

export const useI18n = () => {
  const messages = computed(() => getMessages(currentLanguage.value));
  
  const setLanguage = (lang: string) => {
    currentLanguage.value = lang;
    localStorage.setItem('app-language', lang);
  };

  // 翻译函数 - 支持嵌套路径
  const t = (key: string, params?: Record<string, any>): string => {
    const keys = key.split('.');
    let value: any = messages.value;
    
    for (const k of keys) {
      if (value && typeof value === 'object' && k in value) {
        value = value[k];
      } else {
        return key; // 找不到翻译时返回原key
      }
    }
    
    if (typeof value !== 'string') {
      return key;
    }
    
    // 参数替换 {param}
    if (params) {
      return value.replace(/\{(\w+)\}/g, (match, paramKey) => {
        return params[paramKey] || match;
      });
    }
    
    return value;
  };
  
  return {
    currentLanguage,
    messages,
    setLanguage,
    t
  };
}; 